package com.mcc.app.finish.service.impl;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mcc.common.config.ProjectConfig;
import com.mcc.common.exception.CustomException;
import com.mcc.common.utils.DateUtils;
import com.mcc.common.utils.SecurityUtils;
import com.mcc.common.utils.uuid.IdUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.mcc.app.finish.mapper.FinishedTestAnalysisMapper;
import com.mcc.app.finish.domain.FinishedTestAnalysis;
import com.mcc.app.finish.service.IFinishedTestAnalysisService;

import static com.mcc.common.utils.file.FileUploadUtils.getAbsoluteFile;

/**
 * 成品检化验结果Service业务层处理
 *
 * @author gxy
 * @date 2025-04-03
 */
@Service
public class FinishedTestAnalysisServiceImpl implements IFinishedTestAnalysisService {

    @Autowired
    private FinishedTestAnalysisMapper finishedTestAnalysisMapper;

    /**
     * 查询成品检化验结果
     *
     * @param id 成品检化验结果ID
     * @return 成品检化验结果
     */
    @Override
    public FinishedTestAnalysis selectFinishedTestAnalysisById(Integer id) {
        return finishedTestAnalysisMapper.selectById(id);
    }

    /**
     * 查询成品检化验结果列表
     *
     * @param finishedTestAnalysis 成品检化验结果
     * @return 成品检化验结果
     */
    @Override
    public List<FinishedTestAnalysis> selectFinishedTestAnalysisList(FinishedTestAnalysis finishedTestAnalysis) {
        QueryWrapper queryWrapper = new QueryWrapper();
        if (ObjectUtil.isNotEmpty(finishedTestAnalysis)) {
            queryWrapper.ge(ObjectUtil.isNotEmpty(finishedTestAnalysis.getStartDt()), "release_time", finishedTestAnalysis.getStartDt());
            queryWrapper.le(ObjectUtil.isNotEmpty(finishedTestAnalysis.getEndDt()), "release_time", finishedTestAnalysis.getEndDt());
            queryWrapper.eq(ObjectUtil.isNotEmpty(finishedTestAnalysis.getQualityCode()), "quality_code", finishedTestAnalysis.getQualityCode());
            queryWrapper.eq(ObjectUtil.isNotEmpty(finishedTestAnalysis.getSamplingOrder()), "sampling_order", finishedTestAnalysis.getSamplingOrder());
            queryWrapper.eq(ObjectUtil.isNotEmpty(finishedTestAnalysis.getCompTfe()), "comp_tfe", finishedTestAnalysis.getCompTfe());
            queryWrapper.eq(ObjectUtil.isNotEmpty(finishedTestAnalysis.getCompFeo()), "comp_feo", finishedTestAnalysis.getCompFeo());
            queryWrapper.eq(ObjectUtil.isNotEmpty(finishedTestAnalysis.getCompCao()), "comp_cao", finishedTestAnalysis.getCompCao());
            queryWrapper.eq(ObjectUtil.isNotEmpty(finishedTestAnalysis.getCompMgo()), "comp_mgo", finishedTestAnalysis.getCompMgo());
            queryWrapper.eq(ObjectUtil.isNotEmpty(finishedTestAnalysis.getCompSio2()), "comp_sio2", finishedTestAnalysis.getCompSio2());
            queryWrapper.eq(ObjectUtil.isNotEmpty(finishedTestAnalysis.getCompAl2o3()), "comp_al2o3", finishedTestAnalysis.getCompAl2o3());
            queryWrapper.eq(ObjectUtil.isNotEmpty(finishedTestAnalysis.getCompR2()), "comp_r2", finishedTestAnalysis.getCompR2());
            queryWrapper.eq(ObjectUtil.isNotEmpty(finishedTestAnalysis.getCompP()), "comp_p", finishedTestAnalysis.getCompP());
            queryWrapper.eq(ObjectUtil.isNotEmpty(finishedTestAnalysis.getCompTio2()), "comp_tio2", finishedTestAnalysis.getCompTio2());
            queryWrapper.eq(ObjectUtil.isNotEmpty(finishedTestAnalysis.getCompS()), "comp_s", finishedTestAnalysis.getCompS());
            queryWrapper.eq(ObjectUtil.isNotEmpty(finishedTestAnalysis.getCompMno()), "comp_mno", finishedTestAnalysis.getCompMno());
            queryWrapper.eq(ObjectUtil.isNotEmpty(finishedTestAnalysis.getCompZn()), "comp_zn", finishedTestAnalysis.getCompZn());
            queryWrapper.eq(ObjectUtil.isNotEmpty(finishedTestAnalysis.getCompCr()), "comp_cr", finishedTestAnalysis.getCompCr());
            queryWrapper.eq(ObjectUtil.isNotEmpty(finishedTestAnalysis.getQualified()), "qualified", finishedTestAnalysis.getQualified());
        }
        return finishedTestAnalysisMapper.selectList(queryWrapper);
    }

    /**
     * 新增成品检化验结果
     *
     * @param finishedTestAnalysis 成品检化验结果
     * @return 结果
     */
    @Override
    public int insertFinishedTestAnalysis(FinishedTestAnalysis finishedTestAnalysis) {
        finishedTestAnalysis.setCreateBy(SecurityUtils.getUsername());
        finishedTestAnalysis.setCreateTime(new Date());
        return finishedTestAnalysisMapper.insert(finishedTestAnalysis);
    }

    /**
     * 修改成品检化验结果
     *
     * @param finishedTestAnalysis 成品检化验结果
     * @return 结果
     */
    @Override
    public int updateFinishedTestAnalysis(FinishedTestAnalysis finishedTestAnalysis) {
        finishedTestAnalysis.setUpdateBy(SecurityUtils.getUsername());
        finishedTestAnalysis.setUpdateTime(new Date());
        return finishedTestAnalysisMapper.updateById(finishedTestAnalysis);
    }

    /**
     * 删除成品检化验结果
     *
     * @param id 成品检化验结果ID
     * @return 结果
     */
    @Override
    public int deleteFinishedTestAnalysisById(Integer id) {
        return finishedTestAnalysisMapper.deleteById(id);
    }

    /**
     * 批量删除成品检化验结果
     *
     * @param ids 成品检化验结果ID
     * @return 结果
     */
    @Override
    public int deleteFinishedTestAnalysisByIds(Integer[] ids) {
        if (ids.length == 0) return 0;
        return finishedTestAnalysisMapper.deleteBatchIds(ListUtil.toList(ids));
    }

    @Override
    public String exportStopRecordList(FinishedTestAnalysis finishedTestAnalysis) {
        List<FinishedTestAnalysis> list = selectFinishedTestAnalysisList(finishedTestAnalysis);

        ExcelWriter exportWriter = ExcelUtil.getBigWriter();
        exportWriter.addHeaderAlias("releaseTime", "发布时间");
        exportWriter.addHeaderAlias("qualityCode", "质检编号");
        exportWriter.addHeaderAlias("samplingOrder", "取样单号");
        exportWriter.addHeaderAlias("compTfe", "TFe");
        exportWriter.addHeaderAlias("compFeo", "FeO");
        exportWriter.addHeaderAlias("compCao", "CaO");
        exportWriter.addHeaderAlias("compMgo", "MgO");
        exportWriter.addHeaderAlias("compSio2", "SiO2");
        exportWriter.addHeaderAlias("compAl2o3", "AI2O3");
        exportWriter.addHeaderAlias("compR2", "R2");
        exportWriter.addHeaderAlias("compP", "P");
        exportWriter.addHeaderAlias("compTio2", "TiO2");
        exportWriter.addHeaderAlias("compS", "S");
        exportWriter.addHeaderAlias("compMno", "MnO");
        exportWriter.addHeaderAlias("compZn", "Zn");
        exportWriter.addHeaderAlias("compCr", "Cr");
        exportWriter.addHeaderAlias("qualified", "是否合格");
        exportWriter.addHeaderAlias("remark", "备注");

        exportWriter.setOnlyAlias(true);
        exportWriter.write(list);
        exportWriter.autoSizeColumnAll();
        String filename = IdUtils.fastSimpleUUID() + "_检化验数据" + DateUtil.format(new Date(), "yyyyMMdd") + ".xlsx";
        try {
            OutputStream out = new FileOutputStream(getAbsoluteFile(ProjectConfig.getDownloadPath(), filename));
            exportWriter.flush(out, true);
        } catch (IOException e) {
            e.printStackTrace();
            throw new CustomException("导出失败");
        } finally {
            exportWriter.close();
        }
        return filename;

//        List<FinishedTestAnalysis> stopList = selectFinishedTestAnalysisList(finishedTestAnalysis);
//        List<Map<String, Object>> mapList = new ArrayList<>();
//        for (int i = 0; i < stopList.size(); i++) {
//            FinishedTestAnalysis row = stopList.get(i);
//            if (row.getEndDt() != null) {
//                Map<String, Object> map = new LinkedHashMap<>();
//                map.put("发布时间", DateUtil.formatDateTime(row.getReleaseTime()));
//                map.put("质检编号", row.getQualityCode());
//                map.put("取样单号", row.getSamplingOrder());
//                map.put("TFe", row.getCompTfe());
//                map.put("FeO", row.getCompFeo());
//                map.put("CaO", row.getCompCao());
//                map.put("MgO", row.getCompMgo());
//                map.put("SiO2", row.getCompSio2());
//                map.put("AI2O3", row.getCompAl2o3());
//                map.put("R2", row.getCompR2());
//                map.put("P", row.getCompP());
//                map.put("TiO2", row.getCompTio2());
//                map.put("S", row.getCompS());
//                map.put("MnO", row.getCompMno());
//                map.put("Zn", row.getCompZn());
//                map.put("Cr", row.getCompCr());
//                map.put("是否合格", row.getQualified());
//                map.put("备注", row.getRemark());
//                mapList.add(map);
//            }
//        }
//
//        String filename = IdUtil.fastSimpleUUID() + "_检化验记录" + DateUtils.getDate() + ".xlsx";
//        ExcelWriter exportWriter = ExcelUtil.getWriter();
//        exportWriter.write(mapList, true);
//        try {
//            OutputStream out = new FileOutputStream(getAbsoluteFile(ProjectConfig.getDownloadPath(), filename));
//            exportWriter.flush(out, true);
//        } catch (IOException e) {
//            e.printStackTrace();
//            throw new CustomException("导出失败");
//        } finally {
//            exportWriter.close();
//        }
//        return filename;
    }
}


